package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.DepartmentMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.page.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService{

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageResult query(QueryObject qo) {

        int totalCount = roleMapper.queryForCount(qo);
        if(totalCount == 0){
            return new PageResult();
        }
        List<Role> list = roleMapper.queryForList(qo);
        return new PageResult(totalCount,list);
    }

    @Override
    public void save(Role role) {
        //保存角色
        roleMapper.insert(role);

        //保存角色和权限之间的额关系
        List<Permission> permissions = role.getPermissions();
        if (permissions !=null){

            for (Permission permission : permissions) {

                roleMapper.saveRolePermissionRelation(role.getId(),permission.getId());
            }
        }
        List<Menu> menus = role.getMenus();
        if (menus !=null){

            for (Menu menu : menus) {
                roleMapper.saveRoleMenuRelation(role.getId(),menu.getId());
            }
        }

    }

    @Override
    public void edit(Role role) {
        roleMapper.updateByPrimaryKey(role);

        //删除之前角色和权限之间的旧关系
        roleMapper.deleteRolePermissionRelation(role.getId());
        roleMapper.deleteRoleMenuRelation(role.getId());
        //保存新关系

        List<Permission> permissions = role.getPermissions();
        if (permissions !=null){

            for (Permission permission : permissions) {

                roleMapper.saveRolePermissionRelation(role.getId(),permission.getId());
            }
        }

        List<Menu> menus = role.getMenus();
        if (menus !=null){

            for (Menu menu : menus) {
                roleMapper.saveRoleMenuRelation(role.getId(),menu.getId());
            }
        }
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public List<Integer> listIdsByEmployeeId(Long employeeId) {
        List<Integer> list = roleMapper.listIdsByEmployeeId(employeeId);
        return list;
    }

    @Override
    public List<String> getRoleSnByEmployeeId(Long employeeId) {
        List<String> list =  roleMapper.getRoleSnByEmployeeId(employeeId);

        return list;
    }
}
